<?php

$session = SimpleSAML_Session::getInstance();
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();

$spEntityId = $metadata->getMetaDataCurrentEntityID('saml20-sp-hosted');


$globalConfig = SimpleSAML_Configuration::getInstance();
SimpleSAML_Logger::info('attributeaggregator - attributequery: Accessing attributequery.');

if (!array_key_exists('StateId', $_REQUEST)) {
	throw new SimpleSAML_Error_BadRequest(
			'Missing required StateId query parameter.'
	);
}

$id = $_REQUEST['StateId'];
$state = SimpleSAML_Auth_State::loadState($id, 'attributeaggregator:request');
$aaMetadata = $metadata->getMetadata($state['attributeaggregator:entityId'],'attributeauthority-remote');
$aas = $aaMetadata['AttributeService'];
for ($i=0;$i<count($aas);$i++){
	if ($aas[$i]['Binding'] == SAML2_Const::BINDING_SOAP){
		$index = $i;
		break;
	}
}

$url = $aas[$index]['Location'];
$defNameId = array();

/* EPPN */
$defNameId['Value'] = $state['attributeaggregator:eppn'][0];

/* PERSISTENT */
$defNameId['Format'] = SAML2_Const::NAMEID_PERSISTENT;

$defNameId['NameQualifier'] = '';
$defNameId['SPNameQualifier'] = '';


$data['nameIdFormat'] = $defNameId['Format'];
$data['nameIdValue'] = $defNameId['Value'];
$data['nameIdQualifier'] = $defNameId['NameQualifier'];
$data['nameIdSPQualifier'] = $defNameId['SPNameQualifier'];
/* VO AttributeAuthority endpoint */
$data['url'] = $url;
$data['stateId'] = $id;

$dataId = SimpleSAML_Utilities::generateID();
$session->setData('attributeaggregator:data', $dataId, $data, 3600);

/*if (array_key_exists('send', $_REQUEST)) { */

$nameId = array(
		'Format' => $data['nameIdFormat'],
		'Value' => $data['nameIdValue'],
		'NameQualifier' => $data['nameIdQualifier'],
		'SPNameQualifier' => $data['nameIdSPQualifier'],
);
if (empty($nameId['NameQualifier'])) {
	$nameId['NameQualifier'] = NULL;
}
if (empty($nameId['SPNameQualifier'])) {
	$nameId['SPNameQualifier'] = NULL;
}
$response = sendQuery($dataId, $data['url'], $nameId);

SimpleSAML_Logger::debug('attributeaggregator:attributequery - getting response');

if (!($response instanceof SAML2_Response)) {
	throw new SimpleSAML_Error_Exception('Unexpected message received to attribute query example.');
}

$idpEntityId = $response->getIssuer();
if ($idpEntityId === NULL) {
	throw new SimpleSAML_Error_Exception('Missing issuer in response.');
}
$assertions = $response->getAssertions();
$attributes = $assertions[0]->getAttributes();
//var_dump($attributes); exit;

foreach ($attributes as $k=>$v){
	$current = array();
	if (array_key_exists($k,$state['Attributes'])) {
		$current = $state['Attributes'][$k];
	}
	$new = $v;
	foreach( $new as $c){
		$state['Attributes'][$k][] = $c;
	}
	//$state['Attributes'][$k]=array_merge($current,$new);
}

SimpleSAML_Logger::debug('[attributeaggregator] The whole new attributes:'.var_export($state['Attributes'],true));
SimpleSAML_Auth_ProcessingChain::resumeProcessing($state);
exit;

function sendQuery($dataId, $url, $nameId) {
	assert('is_string($dataId)');
	assert('is_string($url)');
	assert('is_array($nameId)');

	SimpleSAML_Logger::debug('attributeaggregator:attributequery - sending request');

	$query = new SAML2_AttributeQuery();
	$query->setRelayState($dataId);
	$query->setDestination($url);
	$query->setIssuer($GLOBALS['spEntityId']);
	$query->setNameId($nameId);


	$binding = new SAML2_SOAPClient();
	$result = $binding->send($query,SimpleSAML_Configuration::getInstance());
	return $result;
}